package com.luoxiang.lib_common.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.luoxiang.lib_common.R
import com.luoxiang.lib_common.adapter.EvaluateLabelAdapter
import com.luoxiang.lib_common.bean.CallEvaluateInfoBean
import com.luoxiang.lib_common.bean.EvaluationLabel
import com.luoxiang.lib_common.bean.NumberBean
import com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN
import com.luoxiang.lib_common.databinding.DialogEvaluateBinding
import com.luoxiang.lib_common.utils.MmkvUtil
import com.luoxiang.lib_common.utils.NetUtils
import com.lxj.xpopup.impl.FullScreenPopupView
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers


class EvaluateDialog(context: Context) : FullScreenPopupView(context) {
    enum class EvaluateStatus {
        /***
         * 喜欢*/
        LIKE,

        /***
         * 不喜欢*/
        NOT_LIKE
    }

    private lateinit var mViewBinding: DialogEvaluateBinding
    private lateinit var callEvaluateInfoBean: CallEvaluateInfoBean
    private val data: ArrayList<EvaluationLabel> = arrayListOf()
    private lateinit var adapter: EvaluateLabelAdapter
    private var evaluateStatus: EvaluateStatus = EvaluateStatus.LIKE
    private lateinit var channelId: String

    override fun getImplLayoutId() = R.layout.dialog_evaluate

    @SuppressLint("SetTextI18n")
    override fun onCreate() {
        super.onCreate()
        mViewBinding = DialogEvaluateBinding.bind(popupImplView)
        data.addAll(callEvaluateInfoBean.goodLabels)
        adapter = EvaluateLabelAdapter(data)
        Glide.with(context)
            .load("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/"+(callEvaluateInfoBean.hostInfo?.hostIcon?:0))
            .transform(CircleCrop())
            .into(mViewBinding.imageHead)
        mViewBinding.textName.text = callEvaluateInfoBean.hostInfo?.hostName
        mViewBinding.textUserId.text = "ID：${callEvaluateInfoBean.hostInfo?.hostId}"
        mViewBinding.textCallDuration.text = "通话:${callEvaluateInfoBean.callInfo?.totalTime}分钟"
        mViewBinding.textConsumption.text = "消费:${callEvaluateInfoBean.callInfo?.totalConsume}金币"
        mViewBinding.recyclerView.adapter = adapter
        //设置布局管理器
        val flexboxLayoutManager = FlexboxLayoutManager(context)
        flexboxLayoutManager.flexDirection = FlexDirection.ROW
        flexboxLayoutManager.flexWrap = FlexWrap.WRAP
        flexboxLayoutManager.justifyContent = JustifyContent.FLEX_START
        mViewBinding.recyclerView.layoutManager = flexboxLayoutManager
        changeUI()

        mViewBinding.imageLike.setOnClickListener {
            if (evaluateStatus == EvaluateStatus.LIKE) return@setOnClickListener
            evaluateStatus = EvaluateStatus.LIKE
            changeUI()
        }
        mViewBinding.imageNotLike.setOnClickListener {
            if (evaluateStatus == EvaluateStatus.NOT_LIKE) return@setOnClickListener
            evaluateStatus = EvaluateStatus.NOT_LIKE
            changeUI()
        }
        mViewBinding.viewSubmit.setOnClickListener {
            submit()
        }
        mViewBinding.imageClose.setOnClickListener {
            dismiss()
        }
        adapter.setOnItemClickListener { _, _, position ->
            if (adapter.indexItemData.containsKey(data[position].id)) {
                adapter.indexItemData.remove(data[position].id)
            } else {
                adapter.indexItemData[data[position].id] = data[position]
            }
            adapter.notifyDataSetChanged()
        }
    }

    private fun changeUI() {
        when (evaluateStatus) {
            EvaluateStatus.LIKE -> {
                mViewBinding.imageLike.setImageDrawable(
                    ContextCompat.getDrawable(
                        context,
                        R.mipmap.icon_xihuan_50_sel
                    )
                )
                mViewBinding.imageNotLike.setImageDrawable(
                    ContextCompat.getDrawable(
                        context,
                        R.mipmap.icon_buxihuan_50_ccc_nor
                    )
                )
                mViewBinding.textLike.setTextColor(Color.parseColor("#FB4240"))
                mViewBinding.textNotLike.setTextColor(Color.parseColor("#999999"))
                data.clear()
                data.addAll(callEvaluateInfoBean.goodLabels)
                adapter.indexItemData.clear()
                adapter.notifyDataSetChanged()
            }
            EvaluateStatus.NOT_LIKE -> {
                mViewBinding.imageLike.setImageDrawable(
                    ContextCompat.getDrawable(
                        context,
                        R.mipmap.icon_xihuan_50_nor
                    )
                )
                mViewBinding.imageNotLike.setImageDrawable(
                    ContextCompat.getDrawable(
                        context,
                        R.mipmap.icon_buxihuan_50_666_sel
                    )
                )
                mViewBinding.textLike.setTextColor(Color.parseColor("#999999"))
                mViewBinding.textNotLike.setTextColor(Color.parseColor("#333333"))
                data.clear()
                data.addAll(callEvaluateInfoBean.badLabels)
                adapter.indexItemData.clear()
                adapter.notifyDataSetChanged()
            }
        }
    }

    private fun submit() {
        val map = adapter.indexItemData.apply {
            if (isEmpty()) {
                Toast.makeText(context, "请至少选择一个评价", Toast.LENGTH_SHORT).show()
                return
            }else if (size>3){
                Toast.makeText(context,"最多选择三个评价",Toast.LENGTH_SHORT).show()
                return
            }
        }
        val label = StringBuilder()
        map.forEach {
            label.append(it.key.toString())
            label.append(",")
        }
        val labelIds = label.toString().substring(0,label.length-1)
        NetUtils.getInstance().apiService
            .callEvaluate(MmkvUtil.decodeString(TOKEN), channelId, evaluateStatus.ordinal, labelIds)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NumberBean> {
                override fun onSubscribe(d: Disposable?) {}

                override fun onNext(t: NumberBean?) {
                }

                override fun onError(e: Throwable?) {}

                override fun onComplete() {}
            })
        dismiss()
    }

    public fun setData(channelId: String, callEvaluateInfoBean: CallEvaluateInfoBean) {
        this.callEvaluateInfoBean = callEvaluateInfoBean
        this.channelId = channelId
    }
}